package com.atguigu.gmall.order.controller;

import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @Author atguigu-mqx
 * @Description TODO
 * @Date 2023/5/23 15:30
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/order")
public class OrderApiController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 去结算
     * @param request
     * @return
     */
    @GetMapping("/auth/trade")
    public Result trade(HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  调用服务层方法. detailArrayList totalNum totalAmount tradeNo-流水号;
        Map<String,Object> map = orderService.trade(userId);
        //  返回数据
        return Result.ok(map);
    }

    //  http://api.gmall.com/api/order/auth/submitOrder?tradeNo=null
    /**
     * 保存订单
     * @param orderInfo
     * @return
     */
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,
                              HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));

        //  校验流水号是否正确.
        //  获取页面传递的流水号了.
        String tradeNo = request.getParameter("tradeNo");
        //  删除锁应该具有原子性操作. lua 脚本.
        String scriptText = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        //  执行删除命令
        DefaultRedisScript redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(scriptText);
        redisScript.setResultType(Long.class);
        //  存储缓存的key
        String tradeNoKey = "tradeNo:"+userId;
        //  拿页面传递的流水号作为缓存的value 进行比较。比较成功，就删除。
        Long result = (Long) this.redisTemplate.execute(redisScript, Arrays.asList(tradeNoKey), tradeNo);
        //  比较结果。
        if (result==0){
            return Result.fail().message("不能重复回退提交订单.");
        }

        //  创建一个异步编排对象集合
        ArrayList<CompletableFuture> completableFutureArrayList = new ArrayList<>();
        //  创建一个信息集合
        ArrayList<String> errorList = new ArrayList<>();
        //  查询剩余库存. 每个商品都查询.
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        if (!CollectionUtils.isEmpty(orderDetailList)){
            //  订单明细 23,24,25
            for (OrderDetail orderDetail : orderDetailList) {
                //  验证库存
                CompletableFuture<Void> stockCompletableFuture = CompletableFuture.runAsync(() -> {
                    //  调用查询库存接口:
                    Boolean flag = this.orderService.hasStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                    if (!flag) {
                        //  提示信息
                        errorList.add(orderDetail.getSkuId() + "库存不足.");
                    }
                },threadPoolExecutor);
                //  将验证库存信息对象添加到集合。
                completableFutureArrayList.add(stockCompletableFuture);

                //  验证价格
                CompletableFuture<Void> priceCompletableFuture = CompletableFuture.runAsync(() -> {
                    //  校验商品的价格：
                    BigDecimal skuPrice = productFeignClient.getSkuPrice(orderDetail.getSkuId());
                    //  订单的价格是
                    BigDecimal orderPrice = orderDetail.getOrderPrice();
                    //  做价格比较
                    if (skuPrice.compareTo(orderPrice) != 0) {
                        // skuPrice>orderPrice == 1; 涨价;
                        // skuPrice>orderPrice == -1; 降价;
                        //  信息提示
                        String msg = skuPrice.compareTo(orderPrice) == 1 ? "涨价" : "降价";
                        //  获取差价信息。
                        BigDecimal price = skuPrice.subtract(orderPrice).abs();

                        //  获取购物车key
                        String cartKey = RedisConst.USER_KEY_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX;
                        //  hget key field;
                        CartInfo cartInfo = (CartInfo) this.redisTemplate.opsForHash().get(cartKey, orderDetail.getSkuId().toString());
                        cartInfo.setSkuPrice(skuPrice);
                        //  写回缓存.
                        this.redisTemplate.opsForHash().put(cartKey, orderDetail.getSkuId().toString(), cartInfo);
                        //  提示信息
                        errorList.add(orderDetail.getSkuId() + "价格有变动" + msg + price + "￥元");
                    }
                },threadPoolExecutor);
                //  将验证价格信息对象添加到集合
                completableFutureArrayList.add(priceCompletableFuture);
            }
        }
        //  多任务组合
        CompletableFuture.allOf(completableFutureArrayList.toArray(new CompletableFuture[completableFutureArrayList.size()])).join();
        //  判断结果：
        if (errorList.size()>0){
            return Result.fail().message(StringUtils.join(errorList,","));
        }
        //  调用服务层方法
        Long orderId = this.orderService.saveOrderInfo(orderInfo);
        //  默认返回
        return Result.ok(orderId);
    }

    //  查看我的订单 http://139.198.104.58:8200/api/order/auth/1/10?orderStatus=PAID
    /**
     * 根据状态查看我的订单。
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping("/auth/{page}/{limit}")
    public Result getOrderPage(@PathVariable Long page,
                               @PathVariable Long limit,
                               HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  获取订单状态
        String orderStatus = request.getParameter("orderStatus");
        //  创建一个Page 对象
        Page<OrderInfo> orderInfoPage = new Page<>(page,limit);

        //  调用服务层方法.
        IPage<OrderInfo> orderInfoIPage = this.orderService.getOrderPage(orderInfoPage,userId,orderStatus);
        //  返回数据
        return Result.ok(orderInfoIPage);
    }

    /**
     * 根据订单Id 获取到订单对象；
     * @param orderId
     * @return
     */
    @GetMapping("/inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable  Long orderId){
        //  调用服务层方法; 只能获取到订单数据，
        //  return this.orderService.getById(orderId);
        //  这个方法我想要获取到订单，同时还要获取到订单明细.
        return this.orderService.getOrderInfo(orderId);
    }
    //  什么叫子订单.
    //  http://localhost:8204/api/order/orderSplit
    @PostMapping("/orderSplit")
    public List<Map<String, Object>> orderSplit(HttpServletRequest request){
        //  获取参数
        String orderId = request.getParameter("orderId");
        String wareSkuMap = request.getParameter("wareSkuMap");

        //  调用服务层方法
        List<OrderInfo> orderInfoList = this.orderService.orderSplit(Long.parseLong(orderId),wareSkuMap);
        //  循环遍历.
        if (!CollectionUtils.isEmpty(orderInfoList)){
            //  获取到子订单明细数据。
            List<Map<String, Object>> mapList = orderInfoList.stream().map(orderInfo -> {
                //  调用服务层方法.
                Map<String, Object> map = this.orderService.initWare(orderInfo);
                return map;
            }).collect(Collectors.toList());
            //  返回数据
            return mapList;
        }
        //  返回
        return new ArrayList<>();
    }

    /**
     * 提交秒杀订单
     * @param orderInfo
     * @return
     */
    @PostMapping("/inner/seckill/submitOrder")
    Long submitOrder(@RequestBody OrderInfo orderInfo){
        //  调用服务层方法。
        Long orderId = this.orderService.saveOrderInfo(orderInfo);
        return orderId;
    }
}
